package com.yunkaweilai.android.fragment.recharge;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.classic.common.MultipleStatusView;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.recharge.RechargeHuoDongActivity;
import com.yunkaweilai.android.activity.recharge.RechargePayTypeActivity;
import com.yunkaweilai.android.base.BaseFragment;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.model.CalculationSmeRechargeBean;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.RechargeAlipayOrderBean;
import com.yunkaweilai.android.model.RechargeWxInfoBean;
import com.yunkaweilai.android.model.SmeRechargeInfoBean;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.SoundPlayUtils;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.utils.pay.PayResult;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 短信充值
 * Created by Administrator on 2019/2/21.
 */

public class MessageRechargeFragment extends BaseFragment {


    @BindView(R.id.id_tv_message_num)
    TextView idTvMessageNum;
    @BindView(R.id.id_tv_tel)
    TextView idTvTel;
    @BindView(R.id.id_recycler)
    RecyclerView idRecycler;
    @BindView(R.id.id_tv_money)
    TextView idTvMoney;
    @BindView(R.id.id_tv_activity)
    TextView idTvActivity;
    @BindView(R.id.id_llayout_activity)
    LinearLayout idLlayoutActivity;
    @BindView(R.id.id_edt_koulin)
    EditText idEdtKoulin;
    @BindView(R.id.id_tv_end_money)
    TextView idTvEndMoney;
    @BindView(R.id.id_tv_end_message)
    TextView idTvEndMessage;
    @BindView(R.id.id_tv_pay_type)
    TextView idTvPayType;
    @BindView(R.id.id_llayout_pay)
    LinearLayout idLlayoutPay;
    @BindView(R.id.id_btn_pay)
    Button idBtnPay;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    Unbinder unbinder;
    @BindView(R.id.id_view_activity)
    View idViewActivity;
    @BindView(R.id.id_tv_left_activity)
    TextView idTvLeftActivity;
    @BindView(R.id.id_tv_left_koulin)
    TextView idTvLeftKoulin;
    @BindView(R.id.id_ll_normal)
    LinearLayout idllNormal;
    @BindView(R.id.id_layout_error)
    RelativeLayout idLayoutError;
    private String typeName;
    private boolean istoken;
    private Gson gson = new Gson();
    private SmeRechargeInfoBean smeRechargeInfoBean;
    private ArrayList<SmeRechargeInfoBean.DataBean.ListBean> list = new ArrayList<>();
    private CommonAdapter<SmeRechargeInfoBean.DataBean.ListBean> adapter;
    private String activities_id, product_id, sub_store_id;
    private CalculationSmeRechargeBean calculationSmeRechargeBean;
    private RechargeAlipayOrderBean rechargeAlipayOrderBean;
    private static final int SDK_PAY_FLAG = 1;
    private boolean iszfb = true;
    private boolean iskoulin = true;
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Log.e("asd", "handleMessage: " + resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        showToast("支付成功");
                        SoundPlayUtils.play(1);
                        idMultipleStatusView.showLoading();
                        refreshView();
                        initHttp();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showToast("支付失败");
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };
    private void refreshView(){
        product_id = "";
        activities_id = "";
        idTvMoney.setText("");
        idTvEndMoney.setText("");
        iskoulin = false;
        idEdtKoulin.setText("");
        iskoulin = true;
        idTvLeftKoulin.setText("优惠口令");
        idTvActivity.setText("");
        idTvEndMessage.setText("");
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onShopEvent(Event.TypeEvent event) {
        if (event != null) {
            if (event.type == CommonConstants.PAY_TYPE_SUCCESS) {
                if (event.flag) {
                    SoundPlayUtils.play(1);
                    idMultipleStatusView.showLoading();
                    initHttp();
                    refreshView();
                }
            }
        }
    }

    public static MessageRechargeFragment newInstence(String typeName, boolean istoken) {
        MessageRechargeFragment messageRechargeFragment = new MessageRechargeFragment();
        messageRechargeFragment.typeName = typeName;
        messageRechargeFragment.istoken = istoken;
        return messageRechargeFragment;
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_recharge_message;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp();
            }
        });
        initAdapter();
        initHttp();
        initClick();

    }

    private void initClick() {
        idLlayoutActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mAc, RechargeHuoDongActivity.class);
                //把list强制类型转换成Serializable类型
                intent.putExtra(RechargeHuoDongActivity.RECHARGE_TIME_LIST, (Serializable) smeRechargeInfoBean.getData().getActivitiesList());
                startActivityForResult(intent, 105);
            }
        });
        idLlayoutPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mAc, RechargePayTypeActivity.class);
                //把list强制类型转换成Serializable类型
                startActivityForResult(intent, 106);
            }
        });

        idEdtKoulin.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (iskoulin){
                    if (delayRun != null) {
                        //每次editText有变化的时候，则移除上次发出的延迟线程
                        handler.removeCallbacks(delayRun);
                    }
                    //延迟800ms，如果不再输入字符，则执行该线程的run方法
                    handler.postDelayed(delayRun, 800);
                }
            }
        });
        idEdtKoulin.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_NEXT) {
                    handled = true;
                     /*隐藏软键盘*/
                    InputMethodManager inputMethodManager = (InputMethodManager) mAc.getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager.isActive()) {
                        inputMethodManager.hideSoftInputFromWindow(mAc.getCurrentFocus().getWindowToken(), 0);
                    }
                }
                return handled;
            }
        });

        idBtnPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgressDialog();
                if (iszfb){
                    initZFBOrder();
                }else{
                    initWXOrder();
                }
            }


        });

    }
    private RechargeWxInfoBean rechargeWxInfoBean;
    private void initWXOrder() {
        HttpRequest.postUrl(Api.STORE_SMS_RECHARGE_ORDER)
                .addParams("store_num", istoken ? "" : typeName)
                .addParams("product_id", product_id + "")
                .addParams("activities_id", activities_id + "")
                .addParams("password", idEdtKoulin.getText().toString() + "")
                .addParams("pay_method", "wechat")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        dismissProgressDialog();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode){
                            rechargeWxInfoBean = gson.fromJson(json, RechargeWxInfoBean.class);
                            initWxPay();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        dismissProgressDialog();
                    }
                });

    }
    private void initZFBOrder() {
        HttpRequest.postUrl(Api.STORE_SMS_RECHARGE_ORDER)
                .addParams("store_num", istoken ? "" : typeName)
                .addParams("product_id", product_id + "")
                .addParams("activities_id", activities_id + "")
                .addParams("password", idEdtKoulin.getText().toString() + "")
                .addParams("pay_method", "alipay")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        dismissProgressDialog();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            rechargeAlipayOrderBean = gson.fromJson(json, RechargeAlipayOrderBean.class);
                            initAliPay();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        dismissProgressDialog();
                    }
                });

    }
    private IWXAPI iwxapi; //微信支付api
    //微信支付
    private void initWxPay() {
        final RechargeWxInfoBean.DataBean.PayResult payResult = rechargeWxInfoBean.getData().getPayResult();
        iwxapi = WXAPIFactory.createWXAPI(mAc, null); //初始化微信api
        iwxapi.registerApp(payResult.getAppid()); //注册appid  appid可以在开发平台获取

        Runnable payRunnable = new Runnable() {  //这里注意要放在子线程
            @Override
            public void run() {
                PayReq request = new PayReq(); //调起微信APP的对象
                //下面是设置必要的参数，也就是前面说的参数,这几个参数从何而来请看上面说明
                request.appId = payResult.getAppid();
                request.partnerId = payResult.getPartnerid();
                request.prepayId = payResult.getPrepayid();
                request.packageValue = payResult.getPackageX();
                request.nonceStr = payResult.getNoncestr();
                request.timeStamp = payResult.getTimestamp()+"";
                request.sign = payResult.getSign();
                iwxapi.sendReq(request);//发送调起微信的请求
                Log.d(TAG, "run: " + payResult.getAppid());
                Log.d(TAG, "run: " + payResult.getPartnerid());
                Log.d(TAG, "run: " + payResult.getPrepayid());
                Log.d(TAG, "run: " + payResult.getPackageX());
                Log.d(TAG, "run: " + payResult.getNoncestr());
                Log.d(TAG, "run: " + payResult.getTimestamp());
                Log.d(TAG, "run: " + payResult.getSign());
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    //支付宝支付
    private void initAliPay() {
        RechargeAlipayOrderBean.DataBean.PayResultBean payResult = rechargeAlipayOrderBean.getData().getPayResult();
        String encodedSign = "";
        try {
            encodedSign = URLEncoder.encode(payResult.getSign(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final String orderInfo = rechargeAlipayOrderBean.getData().getPayResult_str() + "&sign=" + encodedSign;


        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(mAc);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void initAdapter() {
        adapter = new CommonAdapter<SmeRechargeInfoBean.DataBean.ListBean>(mAc, R.layout.item_message_list, list) {
            @Override
            protected void convert(ViewHolder holder, final SmeRechargeInfoBean.DataBean.ListBean listBean, int position) {
                holder.setText(R.id.id_tv_num, listBean.getTitle() + "");
                holder.setText(R.id.id_tv_price, listBean.getPrice() + "");
                LinearLayout idLayout = holder.getView(R.id.id_layout);
                if (listBean.isclick()) {
                    idLayout.setBackgroundResource(R.drawable.shape_message_kuang_true);
                } else {
                    idLayout.setBackgroundResource(R.drawable.shape_message_kuang_false);
                }
                idLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (int i = 0; i < list.size(); i++) {
                            list.get(i).setIsclick(false);
                        }
                        listBean.setIsclick(true);
                        product_id = listBean.getId() + "";
                        CalculationRecharge();
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        };
        idRecycler.setLayoutManager(new GridLayoutManager(mAc, 3));
        idRecycler.setAdapter(adapter);

    }

    private void initHttp() {
        HttpRequest.postUrl(Api.SMS_RECHARGE_INFO)
                .addParams("store_num", istoken ? "" : typeName)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            idMultipleStatusView.showContent();
                            smeRechargeInfoBean = gson.fromJson(json, SmeRechargeInfoBean.class);
                            if (!"1".equals(smeRechargeInfoBean.getData().getIs_open_store_other_product())) {
                                idLayoutError.setVisibility(View.VISIBLE);
                                idllNormal.setVisibility(View.GONE);
                                if (Utils.isEmpty(smeRechargeInfoBean.getData().getReport_phone()+"")){
                                    idTvTel.setText(Html.fromHtml("未开启自主充值功能<br>服务商电话：" + smeRechargeInfoBean.getData().getReport_phone()));
                                }else{
                                    idTvTel.setText(Html.fromHtml("未开启自主充值功能<br>服务商电话：" + smeRechargeInfoBean.getData().getService_tel()));
                                }

                            }else{
                                idLayoutError.setVisibility(View.GONE);
                                idllNormal.setVisibility(View.VISIBLE);
                            }
                            if (smeRechargeInfoBean.getData().getActivitiesList().size() == 0) {
                                idLlayoutActivity.setVisibility(View.GONE);
                                idViewActivity.setVisibility(View.GONE);
                            } else {
                                idLlayoutActivity.setVisibility(View.VISIBLE);
                                idViewActivity.setVisibility(View.VISIBLE);
                            }
                            sub_store_id = smeRechargeInfoBean.getData().getSubStoreInfo().getSub_store_id() + "";
                            idTvMessageNum.setText(smeRechargeInfoBean.getData().getSmsNum() + "");
                            list.clear();
                            list.addAll(smeRechargeInfoBean.getData().getList());
                            adapter.notifyDataSetChanged();
                        } else {
                            idMultipleStatusView.showError();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        idMultipleStatusView.showError();
                    }
                });

    }


    private void CalculationRecharge() {
        HttpRequest.postUrl(Api.DATA_SME_RECHARGE)
                .addParams("store_num", istoken ? "" : typeName)
                .addParams("product_id", product_id + "")
                .addParams("activities_id", activities_id + "")
                .addParams("sub_store_id", sub_store_id + "")
                .addParams("password", idEdtKoulin.getText().toString() + "")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            calculationSmeRechargeBean = gson.fromJson(json, CalculationSmeRechargeBean.class);
                            idTvMoney.setText(calculationSmeRechargeBean.getData().getResult().getZ_price() + "");
                            idTvEndMoney.setText(calculationSmeRechargeBean.getData().getResult().getS_price() + "");
                            idTvEndMessage.setText(calculationSmeRechargeBean.getData().getResult().getSms_result() + "");

                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });
    }

    private Handler handler = new Handler();
    private Runnable delayRun = new Runnable() {
        @Override
        public void run() {
            CalculationRecharge2();
        }
    };

    private void CalculationRecharge2() {
        HttpRequest.postUrl(Api.DATA_STORE_RECHARGE)
                .addParams("store_num", istoken ? "" : typeName)
                .addParams("product_id", product_id + "")
                .addParams("activities_id", activities_id + "")
                .addParams("sub_store_id", sub_store_id + "")
                .addParams("password", idEdtKoulin.getText().toString() + "")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            CalculationSmeRechargeBean calculationSmeRechargeBeans = gson.fromJson(json, CalculationSmeRechargeBean.class);
                            if (calculationSmeRechargeBeans.getData().getResult().getIs_password() == 1) {
                                idTvMoney.setText(calculationSmeRechargeBeans.getData().getResult().getZ_price() + "");
                                idTvEndMoney.setText(calculationSmeRechargeBeans.getData().getResult().getS_price() + "");
                                idTvEndMessage.setText(calculationSmeRechargeBeans.getData().getResult().getSms_result() + "");
                                calculationSmeRechargeBean = calculationSmeRechargeBeans;
                                idTvLeftKoulin.setText("优惠口令 (" + calculationSmeRechargeBeans.getData().getResult().getPassword_price() + ")");

                            } else {
                                idTvLeftKoulin.setText("优惠口令 (无效口令)");
                                showToast("优惠口令无效");
                            }

                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case 105:
                    String name = data.getStringExtra(RechargeHuoDongActivity.RECHARGE_NAME);
                    activities_id = data.getStringExtra(RechargeHuoDongActivity.RECHARGE_ID);
                    if ("不使用优惠活动".equals(name)){
                        idTvActivity.setText("");

                    }else{
                        idTvActivity.setText(name + "");

                    }
                    CalculationRecharge();
                    break;
                case 106:
                    iszfb = data.getBooleanExtra(RechargePayTypeActivity.IS_PAY_TYPE,true);
                    name = data.getStringExtra(RechargePayTypeActivity.PAY_TYPE_NAME);
                    idTvPayType.setText(name+"");
                    break;
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
